package com.example.shiroredis.security;

import com.example.shiroredis.entity.base.ResultCode;
import com.example.shiroredis.utils.ThreadLocalMap;
import com.example.shiroredis.utils.jwt.CheckResult;
import com.example.shiroredis.utils.jwt.JwtUtils;
import com.example.shiroredis.utils.jwt.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * 重写shiro获得jsessionId的方法
 * 默认从cookie中获得jsessionId ,现从请求头中"Authorization"获得token
 * 第一步 :自定义sessionId获取类
 *
 * @Author: lex
 * @Date: 2018/11/16
 * 登入解析token 的地方
 */
@Slf4j
public class MySessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = "Authorization";

    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public MySessionManager() {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //Preconditions.checkArgument(false, "asdasd");
        String jwtSessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        //如果请求头中有 Authorization 则其值为sessionId
        jwtSessionId = StringUtils.substringAfter(jwtSessionId, "Bearer ");
        String sessionId = null;
        if (!StringUtils.isEmpty(jwtSessionId)) {
            sessionId = this.shiroJwtValidate(jwtSessionId);
            if (StringUtils.isBlank(sessionId)) {
                return null;
            }
            log.warn("shiro识别jessionId成功 [ {} ]",sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        } else {
            ThreadLocalMap.put("errorMsg", ResultCode.CODE_NO_HEAD_TOKEN_ERROR);
            //否则按默认规则从cookie取sessionId
            //return super.getSessionId(request, response);
            return null;
        }
    }

    private String shiroJwtValidate(String jwtSessionId) {
        CheckResult checkResult = JwtUtils.validateJWT(jwtSessionId);
        if (checkResult.isSuccess()) {
            String sessionId = checkResult.getClaims().getId();
            if (sessionId == null) {
                ThreadLocalMap.put("errorMsg",ResultCode.CODE_NO_SESSIONID_TOKEN_ERROR);
                return null;
            }
            return sessionId;
        } else {
            switch (checkResult.getErrCode()) {
                // 签名验证不通过
                case SystemConstant.JWT_ERRCODE_FAIL:
                    ThreadLocalMap.put("errorMsg",ResultCode.CODE_DECODE_ERROR);
                    break;
                // 签名过期，返回过期提示码
                case SystemConstant.JWT_ERRCODE_EXPIRE:
                    ThreadLocalMap.put("errorMsg",  ResultCode.CODE_EXPIRE_TIME_ERROR);
                    break;
                default:
                    break;
            }
            return null;
        }
    }
}
